﻿using System.Collections.Generic;
using System.Linq;

namespace PriceCalculator
{
  public class Calculator
  {
    public static double CalcPrice(int[] books)
    {
      var numberOfBooksInSeries = new List<int>();
      CollectSeries(books, numberOfBooksInSeries);

      var price = CalculatePriceFromSeriesList(numberOfBooksInSeries);

      return price;
    }

    internal static void CollectSeries(int[] numberOfBbooksCounter, List<int> numberOfBooksInSeries)
    {
      bool noMoreBooksDetected;
      do
      {
        noMoreBooksDetected = CollectSerie(numberOfBbooksCounter, numberOfBooksInSeries);
      } while (!noMoreBooksDetected);
    }

    internal static bool CollectSerie(int[] numberOfBbooksCounter, List<int> numberOfBooksInSeries)
    {
      var numberOfBooksInASerie = 0;
      var i = 0;
      foreach (var numberOfBooks in numberOfBbooksCounter)
      {
        if (numberOfBooks > 0)
        {
          numberOfBbooksCounter[i]--;
          numberOfBooksInASerie++;
        }
        i++;
      }

      numberOfBooksInSeries.Add(numberOfBooksInASerie);

      var noMoreBooksDetected = numberOfBooksInASerie == 0;

      return noMoreBooksDetected;
    }

    internal static double CalculatePriceFromSeriesList(List<int> numberOfBooksInSeries)
    {
      const double pricePerBook = 8.0;

      return (from numberOfBooks in numberOfBooksInSeries
              let discountInProcent = CalculateDiscount(numberOfBooks)
              select numberOfBooks*pricePerBook*(100 - discountInProcent)/100).Sum();
    }
  
    internal static double CalculateDiscount(int numberOfBooks)
    {
      switch (numberOfBooks)
      {
        case 2:
          return 5;
        case 3:
          return 10;
        case 4:
          return 20;
        case 5:
          return 25;
      }

      return 0.0;
    }
  
  }
}
